package com.beeway.blackgoose.activity;

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.beeway.blackgoose.R;
import com.beeway.blackgoose.bean.ReultCodeState;
import com.beeway.blackgoose.constants.Config;
import com.beeway.blackgoose.utils.MyCountTimer;
import com.beeway.blackgoose.utils.Utils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

public class RegisterActivity extends AppCompatActivity {
    @ViewInject(R.id.register_title_tv)
    private TextView titleTv;
    @ViewInject(R.id.register_mes_tv)
    private TextView mesTv;
    @ViewInject(R.id.register_line_vw)
    private View lineVw;
    @ViewInject(R.id.register_brack_tv)
    private TextView brackTv;
    @ViewInject(R.id.register_phone_edt)
    private EditText phoneNumberEdt;
    @ViewInject(R.id.register_code_edt)
    private EditText codeEdt;
    @ViewInject(R.id.register_fristpwd_edt)
    private EditText fristPwdEdt;
    @ViewInject(R.id.register_affrimpwd_edt)
    private EditText affrimpwdEdt;
    @ViewInject(R.id.register_register_btn)
    private Button registerAndOkBtn;
    @ViewInject(R.id.register_getcode_btn)
    private TextView getcodeBtn;
    private String urlCode;
    private String urlResgiterOk;
    private String urlType;
    private HttpUtils utils;
    private SharedPreferences sp;
    private HttpHandler<String> handler;
    private boolean isRegister;//判断是否注册过
    private boolean isSuccess;//判断是否注册成功

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        changeShowType();
        utils = new HttpUtils();
    }

    //根据参数选择加载类型
    private void changeShowType() {
        String type = getIntent().getStringExtra(Config.COUPON_TYPE);
        urlType = type;
        if (type != null) {
            if (type.equals(Config.REGISTER_TYPE)) { //注册类型
                setContentView(R.layout.activity_register);
                ViewUtils.inject(this);
                urlCode = Config.PHONE_CODE_URL;
                urlResgiterOk = Config.PHONE_REGISTER_URL;
            } else if (type.equals(Config.FORGET_TYPE)) {//忘记密码类型
                setContentView(R.layout.activity_register);
                ViewUtils.inject(this);
                sp = getSharedPreferences("savepsdfile", MODE_PRIVATE);
                changInitView();
                urlCode = Config.PHONE_UPDATECODE_URL;
                urlResgiterOk = Config.PHONE_UPDATE_URL;
            }
        }
    }

    private void changInitView() {
        //使用了相同的布局 修改值
        titleTv.setText("找回密码");
        mesTv.setVisibility(View.GONE);
        lineVw.setVisibility(View.GONE);
        phoneNumberEdt.setText(sp.getString("name", ""));
        fristPwdEdt.setHint("新密码");
        affrimpwdEdt.setHint("再次输入你的新密码");
        registerAndOkBtn.setText("完成");
    }

    @OnClick({R.id.register_register_btn, R.id.register_getcode_btn, R.id.register_brack_tv})
    public void onClick(View v) {
        String number = phoneNumberEdt.getText().toString().trim();
        String onePwd = fristPwdEdt.getText().toString().trim();
        String twoPwd = affrimpwdEdt.getText().toString().trim();
        final String code = codeEdt.getText().toString().trim();
        switch (v.getId()) {
            case R.id.register_getcode_btn: //获得验证码
                getCode(number);
                break;

            case R.id.register_register_btn: //注册 不仅要密码一致 还要验证码正确 同时还不要被注册过 还要有网
                if (Utils.isMobileNum(number)) {
                    if (code != null && !code.equals("")) {
                        if (Utils.isSixNumber(code)) {
                            boolean state = userPwdCheck(onePwd, twoPwd);
                            if (state) {
                                sendPwdPhoneNumber(number, onePwd, code, urlResgiterOk);  //请求服务器

                            } else {
                                return;
                            }
                        } else {
                            Utils.getToastMessage("请输入6位数验证码");
                        }
                    } else {
                        Utils.getToastMessage("验证码不能为空");
                    }
                } else if (number == null || number.equals("")) {
                    Utils.getToastMessage("手机号不能为空");
                } else {
                    Utils.getToastMessage("请正确输入手机号码");
                    phoneNumberEdt.setText("");
                    affrimpwdEdt.setText("");
                    fristPwdEdt.setText("");
                    codeEdt.setText("");
                }
                break;
            case R.id.register_brack_tv:
                onBackPressed();
        }
    }

    public boolean getCode(String number) {
        if (number != null && !number.equals("")) {
            if (Utils.isMobileNum(number)) {
                getAffrimCode(number, urlCode);
                return true;
            } else {
                Utils.getToastMessage("请正确输入手机号码");
                phoneNumberEdt.setText("");
                return false;
            }
        } else {
            Utils.getToastMessage("手机号不能为空");
            return false;
        }
    }

    //获取验证码
    public void getAffrimCode(String number, String url) {

        Utils.getToastMessage(number + url);
        handler = utils.send(HttpRequest.HttpMethod.POST, url, Config.getPhoneCodeParams(number), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                Utils.getToastMessage(result);
                if (result != null) {
                    ReultCodeState acs = JSONObject.parseObject(result, ReultCodeState.class);
                    if (Config.STATE_SUCESS.equals(acs.getResult())) {
                        isRegister = true;
                        MyCountTimer time = new MyCountTimer(getcodeBtn, 0xFFFFFFFF, 0xFFFFFFFF);//服务器成功 成功才进行倒计时
                        time.start();
                    } else if (Config.STATE_FAIL.equals(acs.getResult())) {
                        isRegister = false;
                        if (urlType.equals(Config.REGISTER_TYPE)) {
                            Utils.getToastMessage("该手机号已经注册过");
                        } else if (urlType.equals(Config.FORGET_TYPE)) {
                            Utils.getToastMessage(acs.getMsg());
                        }
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.getToastMessage("请检测你的网络 ");
            }
        });
    }

    //发送密码和手机号
    public void sendPwdPhoneNumber(String number, String userPwd, String code, String url) {

        handler = utils.send(HttpRequest.HttpMethod.POST, url, Config.getsendPwdPhoneNumber(number, userPwd, code), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                Utils.getToastMessage(result);
                if (result != null) {
                    ReultCodeState acs = JSONObject.parseObject(result, ReultCodeState.class);
                    if (Config.STATE_SUCESS.equals(acs.getResult())) { //注册成功
                        if (urlType.equals(Config.REGISTER_TYPE)) {
                            Utils.getToastMessage("恭喜你注册成功");
                        } else if (urlType.equals(Config.FORGET_TYPE)) {
                            Utils.getToastMessage("恭喜你修改成功");
                        }
                    } else if (Config.STATE_FAIL.equals(acs.getResult())) { //失败
                        Utils.getToastMessage(acs.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });

    }

    //验证两个密码是否一致
    public Boolean userPwdCheck(String onePwd, String twoPwd) {

        if (!onePwd.equals("") && onePwd != null && !twoPwd.equals("") && twoPwd != null) {
            if (onePwd.equals(twoPwd)) {
                return true;
            } else {
                Utils.getToastMessage("密码不一致，请重新输入");
                fristPwdEdt.setText("");
                affrimpwdEdt.setText("");
                return false;
            }
        } else {
            Utils.getToastMessage("密码不能为空");
            return false;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Utils.getAnimOut(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.cancel();
        }
    }
}
